package testJdk.base.gc;

import java.util.HashMap;
import java.util.Map;

/**
 * @author keyer
 * @Description : 演示垃圾回收器的工作时机
 * Created by cyd on 2021-04-23 14:16:53
 */
public class Ghost {
    /**
     * 类持有的缓存区
     */
    private static final Map<String, Ghost> GHOSTS = new HashMap<String, Ghost>();
    private final String name;

    private Ghost(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    /**
     * 工厂方法，如果缓存中有，就直接给；如果没有，就new一个放进缓存，再给
     * @param name key
     * @return ghost实例
     */
    public static Ghost getInstance(String name) {
        Ghost ghost = GHOSTS.get(name);
        if (ghost == null) {
            ghost = new Ghost(name);
            GHOSTS.put(name, ghost);
        }
        return ghost;
    }

    public static void removeInstance(String name) {
        GHOSTS.remove(name);
    }

    @Override
    protected void finalize() {
        GHOSTS.put(this.name, this);
        System.out.println("执行gc");
    }
}

class Test{
    public static void main(String[] args) throws InterruptedException {
        // 获得Ghost的实例，并加入map中
        Ghost jack = Ghost.getInstance("jack");
        System.out.println(jack);
        // 让对象处于可复活状态
        Ghost.removeInstance(jack.getName());
        jack=null;
        // 呼叫gc守护线程
        System.gc();
        // main线程睡眠，加大gc执行的几率
        Thread.sleep(3000);
        Ghost ghost = Ghost.getInstance("jack");
        System.out.println(ghost);
    }
}
